//绑卡列表弹窗
import { useState, useEffect, useMemo } from 'react';
import { Form, Button, Alert, Space, message, Radio, Input } from 'antd';
import CommonModal from '@/components/CommonModal';
import BindNewBankCard from './BindNewBankCard';
import UnbindCardMessage from './UnbindCardMessage';
import { find } from 'lodash';
import { mobile } from '@/utils/rule';
import { bindExistsCard } from './service';
import CommonLoading from '@/components/CommonLoading';
import styles from './index.module.less';

const layout = {
  labelCol: {
    span: 4,
  },
  wrapperCol: {
    span: 20,
  },
};

const BindCardList = ({
  noMesRequire,
  visible,
  pingAnAccount,
  accountExtend,
  handleCancel,
  handleOk,
  handleUnBindOk,
}) => {
  const [value, setValue] = useState(0);
  const [modalVisible, setModalVisible] = useState(false);
  const [cardItem, setcardItem] = useState({}); //选中的银行卡
  const [loading, setLoading] = useState(false);

  const [form] = Form.useForm();

  const onOk = () => {
    // const item = find(pingAnAccount.bindcardList, ['value', value]);
    const item = pingAnAccount.bindcardList[value];
    if (noMesRequire) {
      HandleBindExistsCard(item, pingAnAccount?.mobile);
    } else {
      form
        .validateFields()
        .then((val) => {
          const { mobile } = val;
          const oldMoblieStart = pingAnAccount.mobileNo.slice(0, 3);
          const oldMoblieEnd = pingAnAccount.mobileNo.slice(7, 11);
          if (
            mobile.search(oldMoblieStart) > -1 &&
            mobile.search(oldMoblieEnd) > -1
          ) {
            HandleBindExistsCard(item, mobile);
          } else {
            message.info('手机号与原手机号不一致，请重新输入');
          }
        })
        .catch((err) => {});
    }
  };

  // 二类户绑已存在的卡
  const HandleBindExistsCard = async (item, mobile) => {
    setLoading(true);
    const res = await bindExistsCard({
      bankName: item.bankName,
      bankNo: item.bindCardNo,
      mobile,
    });
    const { success } = res;
    if (success) {
      message.success('绑卡成功！');
      handleOk();
    }
    setLoading(false);
  };

  const onChange = (e) => {
    setValue(e.target.value);
  };

  //银行卡解绑
  const handleUnBind = (item) => {
    const obj = Object.assign(
      { ...item, bankNo: item.bindCardNo },
      { mobile: pingAnAccount.mobile }
    );
    setcardItem(obj);
    setModalVisible('UnbindCardMessage');
  };

  const bindNewCard = () => {
    // if (pingAnAccount.bindcardList && pingAnAccount.bindcardList.length >= 3) {
    //   return message.info('银行卡已超过总数量3张，不能再绑定');
    // }
    setModalVisible('new');
  };

  //新绑定银行卡
  const BindNewBankCardProps = {
    accountExtend,
    pingAnAccount,
    handleOk() {
      handleOk();
      setModalVisible(false);
    },
    handleCancel() {
      setModalVisible(false);
    },
  };

  //银行卡解绑短信弹窗
  const UnbindCardMessageProps = {
    visible: modalVisible == 'UnbindCardMessage',
    cardItem,
    handleCancel() {
      setModalVisible(false);
    },
    handleOk() {
      handleUnBindOk();
      setModalVisible(false);
    },
  };

  return (
    <CommonModal
      title="绑卡列表"
      visible={visible}
      onOk={onOk}
      onCancel={handleCancel}
      width="544px"
      className={styles.addAuthenticationBox}
      footer={[
        <Button
          shape="round"
          className="newRoundBtn2"
          key="close"
          onClick={handleCancel}
        >
          取消
        </Button>,
        <Button
          shape="round"
          size="middle"
          key="ok"
          type="primary"
          onClick={onOk}
        >
          确定
        </Button>,
      ]}
    >
      <div>
        <Alert
          type="info"
          showIcon
          style={{ marginBottom: '24px' }}
          message={`您之前在其他地方已经开过户并且绑过银行卡，请选择其中一张卡作为您在${APP_TITLE}ERP的充值提现卡，
          或者另外新增银行卡绑定。建议优先选择超级卡作为绑定卡`}
        />
        <Button
          style={{ marginBottom: '16px', marginLeft: '23px' }}
          onClick={() => bindNewCard()}
        >
          绑定其他新卡
        </Button>
        <Radio.Group onChange={onChange} value={value}>
          <Space direction="vertical">
            {pingAnAccount.bindcardList.map((item, index) => (
              <Radio key={item.bindCardNo} value={index}>
                <div
                  className={
                    item.value == value
                      ? `${styles.CardListItem} ${styles.slectBorder}`
                      : styles.CardListItem
                  }
                >
                  <div className={styles.CardListSingle}>
                    <div>
                      <span>银行：</span> <span>{item.bankName}</span>
                    </div>
                    <div>
                      <span>卡号：</span> <span>{item.bindCardNo}</span>
                    </div>
                  </div>
                  <div className={styles.CardListSingle}>
                    <div>
                      <span>开户人姓名：</span> <span>{item.userName}</span>
                    </div>
                    <div>
                      <span>单笔/单日充值限额度：</span>
                      <span>{item.rechargeLimitAmount}</span>
                    </div>
                  </div>

                  <div className={styles.CardListSingle}>
                    <div>
                      <span>卡类型：</span>{' '}
                      <span>
                        {item.bindCardLevel == 1 ? '安全卡' : '普通卡'}
                      </span>
                    </div>
                    <div style={{ display: 'flex' }}>
                      <div>
                        <span>卡标志：</span>
                        {item.isSuperCard == 'Y' ? (
                          <span className="common-color9">超级卡</span>
                        ) : (
                          <span>非超级卡</span>
                        )}
                      </div>
                      {item.bindCardLevel == 1 ? (
                        ''
                      ) : (
                        <Button
                          style={{ marginLeft: '20px' }}
                          onClick={() => handleUnBind(item)}
                          shape="round"
                          size="middle"
                        >
                          解除绑定
                        </Button>
                      )}
                    </div>
                  </div>
                </div>
              </Radio>
            ))}
          </Space>
        </Radio.Group>
        {!noMesRequire && (
          <div style={{ marginTop: '20px' }}>
            <Form name="get-phone-code" form={form} {...layout}>
              <Form.Item
                label="手机号"
                name="mobile"
                rules={[{ required: 'true', message: '请输入手机号' }, mobile]}
              >
                <Input placeholder="请输入手机号" size="default" />
              </Form.Item>
            </Form>
            <p style={{ marginLeft: '16px' }}>
              原来开户手机号为{pingAnAccount.mobileNo}
              ，需要您完整输入一遍进行校验
            </p>
          </div>
        )}
      </div>
      {/* 新绑定银行卡 */}
      {modalVisible == 'new' && <BindNewBankCard {...BindNewBankCardProps} />}
      {/* 银行卡短信解绑弹窗 */}
      {modalVisible == 'UnbindCardMessage' && (
        <UnbindCardMessage {...UnbindCardMessageProps} />
      )}
      <CommonLoading loading={loading} />
    </CommonModal>
  );
};

export default BindCardList;
